<template>
  <div>
    <el-dialog
      title="配置角色"
      @close="handleClose"
      :visible.sync="value"
      width="700px"
    >
      <el-checkbox-group v-model="checkList">
        <el-checkbox
          v-for="item in roleList"
          :key="item.id"
          :label="item.title"
          >{{ item.title }}</el-checkbox
        >
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleSubmitRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, updateStaffRole } from "../../../api/role";
export default {
  props: {
    value: {
      type: Boolean,
      required: true,
    },
    role: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      checkList: [],
      roleList: [],
      roleData: [],
    };
  },
  watch: {
    role: {
      handler: function (newValue) {
        if (newValue) {
          this.checkList = newValue.role.map((item) => {
            return item.title;
          });
        }
      },
    },
    checkList: {
      handler: function (newValue) {
        let that = this;
        that.roleData = [];
        let selectRole = that.roleList.filter((item, index) => {
          return that.checkList.includes(item.title);
        });
        that.roleData.push(...selectRole)
      },
    },
  },
  mounted() {
    this.getRoleList();
  },
  methods: {
    handleClose() {
      this.$emit("input", false);
    },
    async getRoleList() {
      let res = await getRoleList();
      this.roleList = res;
    },
    async handleSubmitRole() {
      let id = this.role._id
      let res = await updateStaffRole(id, this.roleData)
      this.$message.success("用户角色更新成功");
      this.$emit("Success")
      this.handleClose();
    },
  },
};
</script>

<style scoped >
</style>
